import json
import requests
import datetime  
import threading 
import concurrent.futures   
import re  
import os  
from Share import share,inquire_share_status
from Login import login
url = "https://perfeye.console.testplus.cn/api/show/tasks"
contition_dict={
   "from": 0,
   "size": 1000,
   "sortField": "",
   "CaseNameKW": "",
    "StartTime": "2024-10-28 00:00:00",
    "EndTime": "2024-10-28 23:59:59"
}
contition = json.dumps(contition_dict)
headers = {
   'Cookie': '',
   'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
   'Content-Type': 'application/json',
   'Accept': '*/*',
   'Host': 'perfeye.console.testplus.cn',
   'Connection': 'keep-alive'
}
# Perfeye列表
perfeye_dict={}
# 锁  
lock = threading.Lock()  
# 记录公开失败时的列表
share_fail_list=[]

# 获取本日日期
def get_today_date():  
    today = datetime.date.today()  
    return today.strftime('%Y-%m-%d')  
# 验证日期合法性
def validate_date(date_str):  
    date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')  
    if date_pattern.match(date_str):  
        try:  
            datetime.datetime.strptime(date_str, '%Y-%m-%d')  
            return True  
        except ValueError:  
            return False  
    return False  
# 查询并设置Perfeye案例公开状态
def get_IsShared_status_by_Id(index):
    IsShared=inquire_share_status(perfeye_dict[index]['ID'],headers)
    with lock:
        perfeye_dict[index]['IsShared'] = IsShared
# 更新条件
def update_contition(key,value):
    global contition
    contition_dict[key]=value
    contition = json.dumps(contition_dict)
# 读取或创建session文件
def read_or_create_session_file(filename='mysession.txt'):  
    try:  
        with open(filename, 'r') as file:  
            mysession = file.read()  
            headers['Cookie']=f"mysession={mysession[::-1]}"
            return mysession[::-1]
    except FileNotFoundError:  
        print("检测到您尚未登录！请登录！按任意键打开登录界面！登录需要谷歌浏览器！")
        print("登录的浏览器界面可能会提示Chrome正受到自动测试软件的控制,这是正常的。")
        os.system("pause>nul")
        print("正在启动浏览器，请在稍后打开的浏览器界面登录...")
        mysession=login()
        with open(filename, 'w') as file:  
            file.write(mysession[::-1])  
        return False

# 输出单条perfeye的url
def print_url(id,appKey):
    if appKey!="":
        print(f"https://perfeye.console.testplus.cn/case/{id}/report?appKey={appKey}")
    else:
        print(f"https://perfeye.console.testplus.cn/case/{id}/report")
# 输出全部perfeye的url
def print_perfeye_data_url():
    for item in perfeye_dict:
        print_url(item['ID'],item['AppKey'])
# 发送请求获取数据
def select_data():
    global perfeye_dict
    try:
        response = requests.request("POST", url, headers=headers, data=contition)
        # 解析响应文本为字典  
        response_dict = json.loads(response.text)  
        if "data" in response_dict:
            perfeye_dict=response_dict["data"]
            # 创建一个ThreadPoolExecutor对象,用线程的方式获取案例的公开状态
            with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: 
                futures = [executor.submit(get_IsShared_status_by_Id, index) for index in range(len(perfeye_dict))]
                # 等待所有任务完成  
                concurrent.futures.wait(futures)  

    except json.decoder.JSONDecodeError:
        print(f"请求失败!请求状态码【{response.status_code}】!请检查mysession是否过期!")
        os.system("pause>nul")
# 输出数据
def input_perfeye_dict():
    print("———————————————————————————————————————————————————")
    for item in perfeye_dict:
        print(f"【{item['AppName']}】:案例名【{item['CaseName']}】,设备号【{item['DeviceType']}】,上报时间【{item['ReportTime']}】,【{'非' if not item['IsShared'] else ''}公开】")
    print("———————————————————————————————————————————————————")


def share_and_record_fail(index):
    global share_fail_list
    if share(perfeye_dict[index]['ID'],headers):
        with lock:
            perfeye_dict[index]['IsShared']=True
    else:
        with lock:
            share_fail_list.append(perfeye_dict[index])
# 公开全部链接
def share_perfeye_data():
    global share_fail_list
    # 重置失败列表
    share_fail_list=[]
    # 创建一个ThreadPoolExecutor对象,用线程的方式公开案例
    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: 
        futures = [executor.submit(share_and_record_fail,index) for index in range(len(perfeye_dict)) if not perfeye_dict[index]['IsShared']]
        # 等待所有任务完成  
        concurrent.futures.wait(futures)  
    for item in share_fail_list:
        print(f"公开【{item['ReportTime']}】的案例【{item['caseName']}】失败！")
    if len(share_fail_list)==0:
        print("公开全部链接成功!")
        return True
    else:
        return False


def lead_set_contition():
    while True:
        startTime = input("请输入要查询的案例开始时间(如2024-01-01,默认为今天): ")
        endTime = input("请输入要查询的案例结束时间(如2024-01-01,默认为今天): ")
        # 处理 startTime  
        if not startTime:  
            startTime = get_today_date()  
        elif not validate_date(startTime):  
            print("开始时间格式不正确，应为 YYYY-MM-DD 格式")  
            # 可以选择退出程序或重新输入，这里选择退出  
            continue
        # 处理 endTime  
        if not endTime:  
            endTime = get_today_date()  
        elif not validate_date(endTime):  
            print("结束时间格式不正确，应为 YYYY-MM-DD 格式")  
            # 可以选择退出程序或重新输入，这里选择退出  
            continue  
        name = input("请输入要查询的案例名(可为空): ")
        update_contition('CaseNameKW',name)
        update_contition('StartTime',f"{startTime} 00:00:00")
        update_contition('EndTime',f"{endTime} 23:59:59")
        break
# 主菜单
def main_menu():
    while True:
        os.system('cls')
        print("———————————————————————————————————————————————————")
        print("当前perfeye案例:")
        input_perfeye_dict()
        print("1. 搜索其他perfeye数据")
        print("2. 公开本页所有perfeye案例")
        print("3. 输出本页所有perfeye案例链接")
        print("q. 关闭程序")
        print("qq. 退出登录并关闭程序")
        print("———————————————————————————————————————————————————")
        choice = input("请输入操作序号以操作: ")
        if choice == '1':
            lead_set_contition()
            select_data()
        elif choice == '2':
            share_perfeye_data()
            os.system("pause>nul")
        elif choice == '3':
            print_perfeye_data_url()
            os.system("pause>nul")
        elif choice.lower() == 'q':
            break
        elif choice.lower() == 'qq':
            # 获取当前工作目录  
            current_directory = os.getcwd()  
            # 构建要删除的文件路径（在当前目录下）  
            file_to_delete = os.path.join(current_directory, 'mysession.txt')  
            # 检查文件是否存在  
            if os.path.exists(file_to_delete):  
                # 删除文件  
                os.remove(file_to_delete)  
            break
        else:
            print("输入有误，请重新输入!")
            os.system("pause>nul")
        continue
# 初始化
def init():
    mysession = read_or_create_session_file()
    while not mysession:
        mysession = read_or_create_session_file()
    # print(lock)
    update_contition('StartTime',f"{get_today_date()} 00:00:00")
    update_contition('EndTime',f"{get_today_date()} 23:59:59")
    select_data()
    main_menu()
if __name__ == "__main__":
    init()
